'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/kh/tjsj/jgjrsj 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		const db = uniCloud.database();
		const $ = db.command.aggregate;
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------

		let dbName = "a_datas"; // 表名

		//先删除原有的临时旧数据
		let deleteOld = await db.collection('a_datas').where({ type: 13 }).remove()

		//计算现有代理商的今日数据
		var time = vk.pubfn.getCommonTime(new Date());
		var todayStart = time.todayStart;
		// var todayEnd = time.todayEnd;

		//====计算每个代理商(包括admin级别)的数据====
		let middlemans = await db.collection('uni-id-users').where({
			role: _.eq(["middleman"])
		}).get()

		let batchRun_middlemans = await vk.pubfn.batchRun({
			// 批量执行函数
			main: async (item, index) => {
				await vk.pubfn.sleep((Math.floor(Math.random() * (3 - 0)) + 0) * 100);
				await compute_middlemans_data(item._id, item)
				return {
					code: 0,
					index
				}
			},
			concurrency: 1, // 最大并发量，如果设置为1，则会按顺序执行
			data: middlemans.data // 数据源，这些数据会依次跑一遍main函数，相当于for循环里的数组
		});
		//====计算每个代理商的数据结束====

		console.log("user_id=", userInfo._id);

		if (userInfo.role.includes("admin")) {
			res = await vk.baseDao.getTableData({
				dbName,
				data,
				whereJson: {
					type: 13 //0为平台总数据，1为账号级数据，2为链接级数据,11为代理商临时数据，13为机构临时数据
				}
			});
			return res;
		} else {
			return res;
		}


		async function compute_middlemans_data(user_id, item) {
			console.log("执行到这里了63行");
			//输入代理商账户ID，生成该代理商昨日数据，第一步先计算昨日新增人数，如为0，则后面无需计算
			if (!user_id) {
				return;
			}

			//查询今日新增用户数
			res.jrxzyhs = await vk.baseDao.count({
				dbName: "uni-id-users",
				whereJson: {
					middleman_id: user_id,
					register_date: _.gt(todayStart)
				}
			});

			//查询今日充值总金额
			res.jrczje = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					middleman_id: user_id,
					pay_status: 1,
					_add_time: _.gt(todayStart)
				}
			});

			//查询今日充值笔数
			res.jrczbs = await vk.baseDao.count({
				dbName: "a_recharge",
				whereJson: {
					middleman_id: user_id,
					pay_status: 1,
					_add_time: _.gt(todayStart)
				}
			});

			//查询今日新用户充值总金额
			res.new_users_moneysum = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					middleman_id: user_id,
					pay_status: 1,
					user_register_date: _.gte(todayStart)
				}
			});

			//====查询新用户充值人数开始====
			let xffyh = await db.collection('a_recharge')
				.aggregate()
				.match({
					middleman_id: user_id,
					pay_status: 1, //状态为支付完成
					user_register_date: _.gte(todayStart)
				})
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			res.newUsers_payNumber = xffyh.data.length ? xffyh.data[0].user_count.length : 0
			console.log("newUsers_payNumber=", res.newUsers_payNumber);
			//====计算新用户充值人数结束====

			//====查询今日充值人数====
			let jrczrs = await db.collection('a_recharge')
				.aggregate()
				.match({
					_add_time: _.gte(todayStart),
					pay_status: 1,
					middleman_id: user_id,
				})
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			res.jrczrs = jrczrs.data.length ? jrczrs.data[0].user_count.length : 0
			//====查询今日充值人数结束====

			//添加到数据库
			let add_datas = await db.collection('a_datas').add({
				middleman_id: user_id,
				middleman_username: item.username,
				middleman_nickname: item.nickname || "无昵称",
				userNumber: res.jrxzyhs,
				rechargeNumber: res.jrczbs,
				rechargeTotal: res.jrczje,
				new_users_moneysum: res.new_users_moneysum, //新用户充值金额
				newUsers_payNumber: res.newUsers_payNumber, //新用户充值人数
				jrczrs: res.jrczrs, //今日充值人数
				type: 13,
				remark: "type=13,为机构账号临时数据"
			})
		}



		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
